import { useEffect, useRef } from 'react'
import * as echarts from 'echarts'

type EChartProps = {
  option: echarts.EChartsOption
  height?: number | string
  width?: number | string
  className?: string
}

function EChart({ option, height = 260, width = '100%', className }: EChartProps) {
  const containerRef = useRef<HTMLDivElement | null>(null)
  const chartRef = useRef<echarts.EChartsType | null>(null)

  useEffect(() => {
    if (!containerRef.current) return
    chartRef.current = echarts.init(containerRef.current)
    const instance = chartRef.current
    instance.setOption(option)

    const onResize = () => {
      instance.resize()
    }
    window.addEventListener('resize', onResize)

    return () => {
      window.removeEventListener('resize', onResize)
      instance.dispose()
      chartRef.current = null
    }
  }, [option])

  useEffect(() => {
    if (chartRef.current) {
      chartRef.current.setOption(option, true)
    }
  }, [option])

  return (
    <div
      ref={containerRef}
      className={className}
      style={{ width, height }}
    />
  )
}

export default EChart

